package com.sxj.PDMS.controller.admin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.context.BaseContext;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.exception.ThrowUtils;
import com.sxj.PDMS.model.dto.admin.MessageRequest;
import com.sxj.PDMS.model.dto.admin.MessageSelectRequest;
import com.sxj.PDMS.model.dto.admin.MessageUpdateRequest;
import com.sxj.PDMS.model.entity.Message;
import com.sxj.PDMS.model.vo.MessageVO;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.service.MessageService;
import com.sxj.PDMS.utils.FileUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.sxj.PDMS.utils.VerifyUtil.formatDate;

@CrossOrigin
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminMessageController {
    @Autowired
    private MessageService messageService;

    @PostMapping("/upload_message")
    public BaseResponse messageUpload(MessageRequest messageRequest) throws IOException, ParseException {
        log.info("文件上传：{}", messageRequest);
        if (messageRequest.getMessage() == null
                && messageRequest.getStudentNumber() == null && messageRequest.getTitle() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String currentId = BaseContext.getCurrentId();
        messageRequest.setAdminId(currentId);

        // todo 文件大小进行限制50mb
        Boolean saved = messageService.messageUpload(messageRequest);
        if (!saved) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        return Result.success();
    }

    @PostMapping("/upload_messageFile")
    public String uploadMessageFile(@RequestPart(value = "uploadFile", required = false) MultipartFile uploadFile) {
        log.info("文件上传：{}", uploadFile);
        if (uploadFile != null && !uploadFile.isEmpty()) {
            synchronized (AdminMessageController.class) {
                //获取当前时间戳
                String flag = System.currentTimeMillis() + "";
                //获取文件名
                String fileName = uploadFile.getOriginalFilename();
                try {
                    //todo：/管理员提交MESSAGE的存放路径
                    String path = "D:\\user\\Desktop\\store\\message\\";
                    FileUtil.writeBytes(uploadFile.getBytes(), path + "\\" + flag + "-" + fileName);
                    System.out.println(fileName + "上传成功");
                    Thread.sleep(1L);
                } catch (Exception e) {
                    System.out.println(fileName + "上传失败");
                }
                return flag;
            }
        } else {
            return "";
        }

    }


    @PutMapping("/modify_message")
    public BaseResponse<Boolean> updateMessage(@RequestBody MessageUpdateRequest messageUpdateRequest) throws ParseException {
        //todo：/管理员提交MESSAGE的存放路径
        String path = "D:\\user\\Desktop\\store\\message\\";
        if (StringUtils.isAnyBlank(messageUpdateRequest.getMessage(), messageUpdateRequest.getAdminId(),
                messageUpdateRequest.getStudentNumber(), messageUpdateRequest.getTitle(),
                messageUpdateRequest.getNewFile(), messageUpdateRequest.getOldFile()) &&
                messageUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        Message message = new Message();
        message.setMessage(messageUpdateRequest.getMessage());
        message.setAdminId(messageUpdateRequest.getAdminId());
        message.setId(messageUpdateRequest.getId());
        message.setStudentNumber(messageUpdateRequest.getStudentNumber());
        message.setTitle(messageUpdateRequest.getTitle());
        if (!Objects.equals(messageUpdateRequest.getNewFile(), "")) {
            // 更新 message 对象的文件时间戳
            message.setFile(messageUpdateRequest.getNewFile());
            //删除旧文件
            Message oldMessage = messageService.getById(messageUpdateRequest.getId());
            String oldFlag = oldMessage.getFile();
            List<String> fileNames = FileUtil.listFileNames(path);
            String avatar = fileNames.stream().filter(name -> name.contains(oldFlag)).findAny().orElse("");
            if (StrUtil.isNotEmpty(avatar)) {
                boolean isDeleted = FileUtil.del(path + avatar);
                if (isDeleted) {
                    log.info("文件 {} 删除成功。", avatar);
                } else {
                    log.error("文件 {} 删除失败。", avatar);
                }
            } else {
                log.warn("文件 {} 不存在，无需删除。", avatar);
            }
        } else {
            message.setFile(messageUpdateRequest.getOldFile());
        }
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        message.setTime(formatDate(currentTime));

        // 更新消息
        boolean result = messageService.updateById(message);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        // todo 记录修改日志
        // log.info("{}:{}修改{}资料文件", new Date().now(), request.getSession().getAttribute("userId"), dataInformationListUpdateRequest.getDataName());

        return Result.success(true);
    }


    @DeleteMapping("/delete_message")
    public BaseResponse<Boolean> deleteMessage(Long Id) {
        //todo：/管理员提交MESSAGE的存放路径
        String path = "D:\\user\\Desktop\\store\\message\\";
        if (Id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //删除文件
        Message message = messageService.getById(Id);
        if (message == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号所指数据不存在");
        }
        boolean removed = messageService.removeById(Id);
        if (!removed) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        String flag = message.getFile();
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        if (StrUtil.isNotEmpty(avatar)) {
            boolean isDeleted = FileUtil.del(path + avatar);
            if (isDeleted) {
                log.info("文件 {} 删除成功。", avatar);
            } else {
                log.error("文件 {} 删除失败。", avatar);
            }
        } else {
            log.warn("文件 {} 不存在，无需删除。", avatar);
        }
        return Result.success(true);
    }

    @GetMapping("/selectAll_message")
    public BaseResponse<PagingQueryResponse<Message>> selectMessage(@RequestParam(defaultValue = "1") Integer page,
                                                                    @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<Message> pagingQueryResponse = messageService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);

    }

    @GetMapping("/select_message")
    public BaseResponse<PagingQueryResponse<MessageVO>> selectWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                          @RequestParam(defaultValue = "10") Integer pageSize,
                                                                          MessageSelectRequest messageSelectRequest) {

        PagingQueryResponse<MessageVO> pagingQueryResponse = messageService.messageSelect(page, pageSize, messageSelectRequest);

        return Result.success(pagingQueryResponse);
    }

    @ApiOperation(value = "downloadMessage", produces = "application/octet-stream")
    @GetMapping("/download_message")
    public void downloadMessage(HttpServletResponse response,
                                String downloadFile) throws Exception {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file", downloadFile);
        Message message = messageService.getOne(queryWrapper);
        if (message == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "库中没有该文件");
        }
        log.info("下载文件：{}", downloadFile);
        //todo://message存放位置
        String path = "D:\\user\\Desktop\\store\\message\\";
        OutputStream outPutStream;
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(downloadFile)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(path + "\\" + avatar);
                outPutStream = response.getOutputStream();
                outPutStream.write(bytes);
                outPutStream.flush();
                outPutStream.close();
            }
        } catch (Exception e) {
            System.out.println(avatar + "下载失败");
        }
    }

    /**
     * 查询消息的具体内容
     *
     * @param id
     * @return
     */
    @GetMapping("/select_message_by_id/{id}")
    public Message selectMessageById(@PathVariable Long id) {
        log.info("查询id:{}", id);
        return messageService.getById(id);
    }
}
